using System.Runtime.InteropServices;

namespace HZY.Core.UploadFile;

public class FileOptions
{
    public string ServerUrl { get; set; } = string.Empty;

    public string DirectoryUrl { get; set; } = string.Empty;

    private readonly string _requestPath = string.Empty;

    public string RequestPath
    {
        get => _requestPath;
        init
        {
            if (!value.StartsWith('/') && !value.StartsWith('\\'))
            {
                value = "/" + value;
            }

            if (value.EndsWith('/') && value.EndsWith('\\'))
            {
                value = value[..^1];
            }

            _requestPath = value;
        }
    }

    public string MaxRequestBodySize { get; set; } = "100MB";

    public string MaxFileSizeLimit { get; set; } = "10MB";

    public string AllowExtensions { get; set; } = "*";

    private long _maxRequestBodySize = -1;

    private long _maxFileSizeLimit = -1;

    /// <summary>
    /// 获取配置的文件路径
    /// </summary>
    /// <param name="rootPath">根路径</param>
    /// <returns></returns>
    public string GetFilePath(string rootPath)
    {
        if (IsPathRooted(DirectoryUrl))
        {
            return DirectoryUrl;
        }

        return Path.Combine(rootPath, DirectoryUrl);
    }

    /// <summary>
    /// 判断地址是否是根路径
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public bool IsPathRooted(string path)
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return Path.IsPathRooted(path);
        }
        else
        {
            return path.StartsWith('/'); // Linux 判断
        }
    }

    /// <summary>
    /// 获取最大请求内容体长度
    /// </summary>
    /// <returns></returns>
    public long GetMaxRequestBodySize()
    {
        if (_maxRequestBodySize != -1)
        {
            return _maxRequestBodySize;
        }

        try
        {
            var value = MaxRequestBodySize.ToStorageByteLength();
            _maxRequestBodySize = value;
        }
        catch (Exception)
        {
            throw new Exception("MaxRequestBodySize 格式错误");
        }

        return _maxRequestBodySize;
    }

    /// <summary>
    /// 获取最大文件长度
    /// </summary>
    /// <returns></returns>
    public long GetMaxFileSizeLimit()
    {
        if (_maxFileSizeLimit != -1)
        {
            return _maxFileSizeLimit;
        }

        try
        {
            var value = MaxFileSizeLimit.ToStorageByteLength();
            _maxFileSizeLimit = value;
        }
        catch (Exception)
        {
            throw new Exception("MaxFileSizeLimit 格式错误");
        }

        return _maxFileSizeLimit;
    }
}